from marajo.appengine.handlers import RequestHandler
from marajo.appengine.api.users import User
from marajo.exceptions import Unauthorized, NotFound
from resources.project import Project
from resources.ticket import Ticket
from resources.comment import Comment
from datetime import datetime


import logging
log = logging.getLogger("vermouth.stats_handler")

class StatsHandler(RequestHandler):
    """
    Statistics about Project hours for the last month
    """

    def get(self):
        """
        Get all hours associated with this user's projects, 
        filtered by "project=ID", for this month

        If no project is specified, we return a list or projects 
        this user can access 
        
        This is done by calculating all the hours for any 
        comment created this month. associated with a ticket 
        that exists in a project this user has access to
        """
        type = self.request.GET.get("type", "project").lower()
        if type == "my_hours":
            now = datetime.now()
            today = self.get_hours(self.user.key(), datetime(month=now.month, year=now.year, day=now.day))
            mtd = self.get_hours(self.user.key(), datetime(month=now.month, year=now.year, day=1))
            self.display("stats_mine.tmpl", {"today": float(today)/60, "mtd": float(mtd)/60})
        else:
            project = self.request.GET.get("project")
            if project:
                project = Project.get_by_id(project)
                if not Project:
                    raise NotFound()
                if not self.user in project.members:
                    raise Unauthorized()
                project_minutes = 0
                now = datetime.now()
                start_of_month = datetime(now.year, now.month, 1)
                for t in Ticket.find(project=project):
                    c_query = t.comments
                    c_query.filter("date >", start_of_month)
                    for c in c_query:
                        project_minutes += c.minutes

                return self.display("stats_hours.tmpl", {"project": project, "project_hours": float(project_minutes)/60})
            else:
                query = Project.find(members=self.user.key())
                return self.display("stats_projects.tmpl", {"projects": query})

    def get_hours(self, user, start_date):
        """Get the total hours for a user based on start_date"""
        query = Comment.find(owner=user)
        query.filter("minutes !=", 0)
        query.filter("date >", start_date)
        minutes = 0
        for c in query:
            minutes += c.minutes
        return minutes
